import utils from '@/utils/index';
import Taro from '@tarojs/taro';

const PayType = {
  wx: 'WXPAY',
  digital: 'DIGICCY',
};

const PayState = {
  success: 'success',
  cancel: 'cancel',
  fail: 'fail',
  unknown: 'unknown',
};

async function wechatPay(orderId, extra) {
  return new Promise((resolve) => {
    Taro.requestPayment({
      ...extra,
      success: function () {
        resolve({
          state: PayState.success,
          orderId,
        });
      },
      fail: function (rlt) {
        if (rlt.errMsg && rlt.errMsg == 'requestPayment:fail cancel') {
          resolve({
            state: PayState.cancel,
            orderId,
            txt: '支付取消',
          });
        } else {
          resolve({
            state: PayState.fail,
            orderId,
            txt: '支付失败',
          });
        }
      },
    });
  });
}

/**
 *  微信支付, h5 和 小程序 都能用
 * @param {string} orderId 订单ID
 * @param {object} extra 服务器返回的支付结构
 * @returns {Promise} 成功 resolve, 取消/失败/未知 reject, 详细内容在 error.extra 中
 */
export async function wxPay(orderId, extra) {
  const data = await wechatPay(orderId, extra).catch((e) => {
    console.warn(e);
    return {
      state: PayState.unknown,
      orderId,
      txt: '未知错误',
    };
  });

  if (data.state === PayState.success) {
    return data;
  }

  let e = new Error(data.txt);
  e.extra = data;

  throw e;
}

// 买单支付
export async function shopPay(
  dispatch,
  {
    merchantId,
    orgId,
    orgName,
    totalPayment,
    totalPrice,

    giftCardIdList,
    orderId,

    customerRemark,
    pointsList,
  },
) {
  let openId = await Taro.getOpenId();

  const data = {
    channel: Taro.$channel,
    payType: PayType.wx,
    openId,

    merchantId,
    orgName,
    orgId,
    totalPayment,
    totalPrice,

    giftCardIdList,
    orderId,

    customerRemark,
    pointsList,
  };

  Taro.$post('/product/product/pay/payBill',data).then(bill=>{
    // 支付金额为零, 无需调起微信支付
    if (parseFloat(totalPayment) === 0) {
      return {
        orderId: bill.orderId,
      };
    }
  
    const payResult = JSON.parse(bill.payResult);
    const extra = JSON.parse(payResult.extra);
  
    return wxPay(bill.orderId, extra);
  })
}
